package com.myapp.ruyixing.ui.widget;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

public class DatePickerFragment extends DialogFragment {

	private OnDateSetListener mOnDateSetListener;

	public static DatePickerFragment getDatePickerFragment() {
		return new DatePickerFragment();
	}

	public static DatePickerFragment getDatePickerFragment(Calendar c) {
		DatePickerFragment fragment = getDatePickerFragment();

		Bundle bundle = new Bundle();
		bundle.putInt("year", c.get(Calendar.YEAR));
		bundle.putInt("month", c.get(Calendar.MONTH));
		bundle.putInt("day", c.get(Calendar.DAY_OF_MONTH));

		fragment.setArguments(bundle);

		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		if (getParentFragment() instanceof OnDateSetListener) {
			mOnDateSetListener = (OnDateSetListener) getParentFragment();
		} else if (activity instanceof OnDateSetListener) {
			mOnDateSetListener = (OnDateSetListener) activity;
		}
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		int year, month, day;
		if (getArguments() != null) {
			year = getArguments().getInt("year");
			month = getArguments().getInt("month");
			day = getArguments().getInt("day");
		} else {
			// Use the current date as the default date in the picker
			final Calendar c = Calendar.getInstance();
			year = c.get(Calendar.YEAR);
			month = c.get(Calendar.MONTH);
			day = c.get(Calendar.DAY_OF_MONTH);
		}

		// Create a new instance of DatePickerDialog and return it
		return new DatePickerDialog(getActivity(), mOnDateSetListener, year,
				month, day);
	}
}
